/*
 * Copyright 2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsHibernateUtil;
import org.springframework.orm.hibernate3.HibernateTemplate
import org.springframework.orm.hibernate3.HibernateCallback
import org.hibernate.Session
import org.hibernate.SessionFactory
import org.hibernate.criterion.Example
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.MatchMode
import org.hibernate.criterion.Projections

/**
 * 
 * @author Shiro Kasahara 
 */
class ScaffoldExGrailsPlugin {
    def version = 0.1
    def dependsOn = [:]

    def author = "Shiro Kasahara"
    def authorEmail = "kasahara.shiro@gmail.com"
    def title = "Plugin summary/headline"
    def description = '''Plugin to use .
'''

    def documentation = "http://code.google.com/p/scaffold-ex/"

    def doWithDynamicMethods = { ctx ->
        for (dc in application.domainClasses) {
            def sessionFactory = ctx.sessionFactory
            def template = new HibernateTemplate(sessionFactory)
            def mc = dc.metaClass
            def clazz = dc.clazz
            def props = dc.persistentProperties
            
            mc.'static'.countEx = {Object example ->
                template.execute({Session session ->
                    def criteria = createCriteria(session, clazz, example)
                    joinAnyToOne(criteria, props, example)
                    criteria.setProjection(Projections.rowCount())
                    criteria.uniqueResult()
                } as HibernateCallback)
            }
            
            mc.'static'.findAllEx = {Object example, Map args ->
                template.execute({Session session ->
                    def criteria = createCriteria(session, clazz, example)
                    GrailsHibernateUtil.populateArgumentsForCriteria(criteria, args)
                    joinAnyToOne(criteria, props, example)
                    criteria.list()
                } as HibernateCallback)
            }
        }
    }
    
    private createCriteria(session, clazz, example) {
        session.createCriteria(clazz)
            .add(Example.create(example)
            .enableLike(MatchMode.ANYWHERE)
            .ignoreCase())
    }
    
    private joinAnyToOne(criteria, props, example) {
        example.properties.each { k, v->
            def prop = props.find({it.name == k})
            if (prop && v && (prop.isOneToOne() || prop.isManyToOne())) {
                criteria = criteria.createCriteria(k)
                    .add(Expression.eq("id", v.id))
            }
        }
    }
}
